#include <iostream>
using std::cout;
using std::endl;

class Singleton
{
public:
    static Singleton * getInstance(){
        //当多个线程同时进入if语句，会造成单例对象被创建出多个
        //然而只有一个地址值会保存到_pInstance
        //因此造成内存泄露
        if(nullptr == _pInstance){
            atexit(destroy);
            _pInstance = new Singleton(1,2);
        }
        return _pInstance;
    }

    void init(int x,int y){
        _ix = x;
        _iy = y;
    }

    void print(){
        cout << "(" << this->_ix
            << "," << this->_iy
            << ")" << endl;
    }

    static void destroy(){
        if(_pInstance){
            cout << ">> delete heap" << endl;
            delete _pInstance;
            _pInstance = nullptr;
        }
    }

private:
    Singleton() = default;

    Singleton(int x ,int y)
    : _ix(x)
    , _iy(y)
    {
        cout << "Singleton(int,int)" << endl;
    }
    
    //一般，析构函数的访问权限与构造函数相同，或者更严格
    ~Singleton(){
        cout << "~Singleton()" << endl;
    }

    //C++11提供的写法
    Singleton(const Singleton & rhs) = delete;
    Singleton & operator=(const Singleton & rhs) = delete;
private:
    int _ix;
    int _iy;
    static Singleton * _pInstance;
};
//饱汉式（懒汉式）—— 懒加载，用到单例对象的时候才创建
/* Singleton * Singleton::_pInstance = nullptr; */

//饿汉式 —— 最开始就把对象创建
//能够确保这里的getInstance是第一次被调用的
Singleton * Singleton::_pInstance = Singleton::getInstance();


void test0(){
    Singleton::getInstance()->init(19,78);
    Singleton::getInstance()->print();
    Singleton::getInstance()->init(76,28);
    Singleton::getInstance()->print();
    Singleton::destroy();
}

int main(void){
    test0();
    return 0;
}
